import os
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
from email.utils import parseaddr, formataddr
import static
from common.utils.config_util import EnvConfig


class Receiver:
    def __init__(self, email, name):
        self.email = email
        self.name = name


class EmailClient:
    def __init__(self):
        env_config = EnvConfig.get_config()
        email_config = env_config['email']
        self.host = email_config['server']['host']
        self.port = email_config['server']['port']
        self.from_info = email_config['from']
        self.server = smtplib.SMTP(self.host, self.port)
        self.server.login(self.from_info['address'], self.from_info['password'])

    def send(self, receivers, subject, content, content_type='plain', file_path=None):
        msg = MIMEMultipart()
        mime_text = MIMEText(content, content_type, 'UTF-8')
        msg.attach(mime_text)
        if file_path:
            msg.attach(EmailClient.get_attach(file_path))
        from_name = self.from_info['name']
        from_email = self.from_info['address']
        msg['From'] = EmailClient.format_addr(f'{from_name} <{from_email}>')
        receiver_list = [f'{receiver.name} <{receiver.email}>' for receiver in receivers]
        receiver_info = ','.join(receiver_list)
        receiver_emails = [receiver.email for receiver in receivers]
        msg['To'] = EmailClient.format_addr(receiver_info)
        msg['Subject'] = Header(subject, 'utf-8').encode()
        return self.server.sendmail(from_email, receiver_emails, msg.as_string())

    @classmethod
    def get_attach(cls, file_path):
        # 添加附件就是加上一个MIMEBase，从本地读取一个图片:
        with open(file_path, 'rb') as f:
            # 获取文件名
            file_name = os.path.split(file_path)[1]
            # 设置附件的MIME和文件名，这里是png类型:
            mime = MIMEBase('zip', 'zip')
            # 加上必要的头信息:
            mime.add_header('Content-Disposition', 'attachment', filename=file_name)
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            # 把附件的内容读进来:
            mime.set_payload(f.read())
            # 用Base64编码:
            encoders.encode_base64(mime)
            return mime

    def close(self):
        self.server.quit()

    @classmethod
    def format_addr(cls, name_address):
        name, address = parseaddr(name_address)
        return formataddr((Header(name, 'utf-8').encode(), address))


if __name__ == '__main__':
    receiver1 = Receiver('15261869092@163.com', '郭亮')
    client = EmailClient()
    html_content = '<html><body>' \
                   '<h1>Hello</h1>' \
                   '<p>send by <a href="http://www.python.org">Python</a>...</p>' \
                   '</body></html> '
    plain_content = '这是邮件正文'
    file_path = os.path.join(static.PROJECT_PATH, 'test_data', 'rabbit_platform', 'files', 'test_file.zip')
    result = client.send([receiver1], '这是邮件主题', plain_content, file_path=file_path)
    print(result)
    client.close()
